package com.hxk.juc.thread.prodCons;

/**
 * Synchronized+wait+notifyAll版生产者消费者案例
 */
public class SynchronizedProdConsCase {

    public static void main(String[] args) {
        SyncData syncData = new SyncData();

        //5台机器生产
        for (int i = 1; i <= 5; i++) {
            new Thread(()->{syncData.prodM();},i+"号机器").start();
        }
        //5个销售人员往外销售
        for (int i = 1; i <= 5; i++) {
            new Thread(()->{syncData.consM();;},i+"号销售").start();
        }
    }
}

class SyncData{

    //库存
    private int num = 0;

    /**
     * 生产方法
     */
    public synchronized void prodM() {
        //判断库存
        while (num != 0){
            try {
                this.wait();//wait必须使用while进行判断，不然会出现虚假唤醒的情况
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //生产
        num++;
        System.out.println(Thread.currentThread().getName()+"\t 库存:"+(num-1)+" 生产:"+num);
        //唤醒消费线程
        this.notifyAll();
    }

    /**
     *  消费方法
     */
    public synchronized void consM(){
        //判断库存
        while (num == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //消费
        num--;
        System.out.println(Thread.currentThread().getName()+"\t 库存:"+(num+1)+" 消费:"+num);
        //唤醒生产线程去生产
        this.notifyAll();
    }
}
